﻿using AutoMapper;
using MediatR;
using ProductionManagement.Application.Command.PickCommand;
using ProductionManagement.Domain.Dtos;
using ProductionManagement.Domain.ProductionDomain;
using ProductionManagement.Infrstructre.lnterface;
using SqlSugar;

namespace ProductionManagement.Application.CommandHandler.PickCommandHandlers
{
    public class UptPickCommandHandlers:IRequestHandler<UptPickCommand, int>
    {

        private readonly IMapper mapper;
        private readonly IPickRepository _pick;
        private readonly IPickProductRepository _pickProduct;
        private readonly ISqlSugarClient db;


        public UptPickCommandHandlers(IMapper mapper, IPickRepository pick, IPickProductRepository pickProduct, ISqlSugarClient db)
        {
            this.mapper = mapper;
            _pick = pick;
            _pickProduct = pickProduct;
            this.db = db;
        
        }

        public async Task<int> Handle(UptPickCommand request, CancellationToken cancellationToken)
        {

            db.Ado.BeginTran();
            try
            {
                //1.先修改领料单
                var result = (await _pick.GetAll()).Where(x => x.PickingId == request.UptDTO.PickingId).First();

                //var query = mapper.Map(Picking,request.UptDTO);
                 //var res = await _pick.UpdAsync(query);
                 var res =   await _pick.UpdAsync(mapper.Map(request.UptDTO, result));

                //删除原有的领料单明细
                var list = (await _pickProduct.GetAll()).Where(x => x.PickingId == request.UptDTO.PicNumber).ToList();
                var res1 = await _pickProduct.DelRange(list);

                foreach(var item in request.UptDTO.PickProdto)
                {
                    PickProduct newItem = new PickProduct
                    {
                        PickingId = request.UptDTO.PicNumber,
                        ProductId = item.ProductId,
                        ManpowerId = item.ManpowerId,
                        OutManager = item.OutManager,
                        OutshipState = item.OutshipState,
                        PickProductDelDate = item.PickProductDelDate,
                        PickProductId = item.PickProductId,
                        PickProductNum = item.PickProductNum,
                        AddName = item.AddName,
                        AddTime = item.AddTime,
                        Office_Id = item.Office_Id,
                        User_Id = item.User_Id,
                    };
                  var res2=   await _pickProduct.AddAsync(newItem);
                }



                db.Ado.CommitTran();
                return 1;
            }
            catch (Exception)
            {


                db.Ado.RollbackTran();
                throw;
            }
           
        }
    }
}
